package com.pig4cloud.pigx.gateway.websocket;

import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.yeauty.annotation.*;
import org.yeauty.pojo.ParameterMap;
import org.yeauty.pojo.Session;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@ServerEndpoint(port = 10001)
@Component
@Slf4j
public class MyWebSocket {

	static Set<Session> sessionSet = new HashSet<Session>();

	@OnOpen
	public void onOpen(Session session, HttpHeaders headers, ParameterMap parameterMap) throws IOException {
		System.out.println("new connection");

		String paramValue = parameterMap.getParameter("paramKey");

		sessionSet.add(session);

		log.info(paramValue);
	}

	@OnClose
	public void onClose(Session session) throws IOException {
		sessionSet.remove(session);
		log.info("one connection closed");
	}

	@OnError
	public void onError(Session session, Throwable throwable) {
		sessionSet.remove(session);
		throwable.printStackTrace();
	}

	@OnMessage
	public void onMessage(Session session, String message) {
		System.out.println(message);
		sessionSet.stream().forEach(item ->  {
			if(item.isActive()){
				item.sendText(message);
			}
			});
	}

	@OnBinary
	public void onBinary(Session session, byte[] bytes) {
		for (byte b : bytes) {
			System.out.println(b);
		}
		session.sendBinary(bytes);
	}

	@OnEvent
	public void onEvent(Session session, Object evt) {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
			switch (idleStateEvent.state()) {
				case READER_IDLE:
					System.out.println("read idle");
					break;
				case WRITER_IDLE:
					System.out.println("write idle");
					break;
				case ALL_IDLE:
					System.out.println("all idle");
					break;
				default:
					break;
			}
		}
	}
}
